# coding=utf-8
import os
import psutil
import time

def get_process_id(name):
    pids = psutil.pids()
    res=[]
    for pid in pids:
        try:
            p = psutil.Process(pid)
            if name in p.name():
                res.append(pid)
        except:
            pass
    return res

def check_no_capacity():
    no_capactiy=1
    is_exist=1 if os.path.exists('hpool.log') else 0
    if is_exist:
        with open('hpool.log','r') as f:
            lines=f.readlines()
            if lines and 'capacity=' in lines[-1]:
                no_capactiy=0
    return no_capactiy

def check_capacity():
    capactiy=0
    is_exist=1 if os.path.exists('hpool.log') else 0
    if is_exist:
        l1,l2=0,0
        size1,size2=0,0
        with open('hpool.log','r') as f:
            lines=f.readlines()
            l1=len(lines)
            if lines and 'capacity=' in lines[-1]:
                start=lines[-1].index('capacity')
                size1=lines[-1][start:].split('"')[1]
            else:
                return 0 
        
        while size1!=size2:
            time.sleep(5)
            with open('hpool.log','r') as f:
                lines=f.readlines()
                l2=len(lines)
                if lines and l2!=l1 and 'capacity=' in lines[-1]:
                    start=lines[-1].index('capacity')
                    size2=lines[-1][start:].split('"')[1]
                    if size1==size2:
                        return size1
    return capactiy

def restart_hpool():
    no_capactiy=15
    pids=[]
    while no_capactiy:
        if no_capactiy>=15:
            # 15秒超时了啊，要重启了只能
            pids = get_process_id("hpool")
            result=os.system('nohup ~/hpool/linux/hpool-miner-chia -config ~/hpool/linux/config.yaml > hpool.log &')  
            no_capactiy=1
        time.sleep(1)
        no_capactiy+=1
        if check_capacity():
            no_capactiy=0
            time.sleep(2)
            print ('restart hpool success')
        
        
    for pid in pids:
        os.system("kill -9 {}".format(pid))
        print (pid)
